package com.retail.bbq.cola.controller;


import com.retail.bbq.cola.annotation.EncryptResponse;
import com.retail.bbq.cola.enums.CommonEnum;
import com.retail.bbq.cola.service.ApiForwardService;
import com.retail.bbq.cola.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api-forward")
@Slf4j
public class ApiForwardController {
    ;
    @Resource
    private ApiForwardService apiForwardService;

    @EncryptResponse
    //@DecryptResponse
    @RequestMapping("/**")
    public ResultVO<?> forwardRequest(
            HttpMethod method,
            HttpServletRequest request,
            @RequestBody(required = false) String body,
            @RequestParam MultiValueMap<String, ?> params,
            @RequestHeader HttpHeaders headers) {
        //TODO 抽奖所有接口转发流程(暂时不做了，可乐所有接口交给前端处理)
        if (method == HttpMethod.POST && StringUtils.isEmpty(body)) {
            return ResultVO.error(CommonEnum.BODY_NOT_MATCH);
        }

        // 获取实际请求路径(去掉前缀)
        String path = (String) request.getAttribute(
                HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        // 调用转发服务
        return apiForwardService.forward(path.replaceFirst("/api-forward", ""),
                method, params, headers, body);
    }


}
